package zencstudio.sgrealtor.view.phone;

import java.util.List;

import zencstudio.sgrealtor.R;
import zencstudio.sgrealtor.adapter.FeedbackTemplateListAdapter;
import zencstudio.sgrealtor.model.FeedbackTemplate;
import zencstudio.sgrealtor.service.WireFrameServiceFactory;
import zencstudio.sgrealtor.utils.Const;
import zencstudio.sgrealtor.utils.WFErrorCode;
import zencstudio.sgrealtor.utils.WFUtils;
import zencstudio.sgrealtor.view.common.BaseActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;


public class FeedBackTemplateActivity extends BaseActivity{
	
	private ListView listTemplate;
	private FeedbackTemplateListAdapter templateAdapter;
	public void onCreate(Bundle saveInstance){
		super.onCreate(saveInstance);
		if(!WFUtils.checkInternetConnection(this)){
			showNetworkErrorDlg();
			return;
		}
	}
	@Override
	protected void initUI() {
		setContentView(R.layout.feedback_template);
		TextView title = (TextView) findViewById(R.id.txtTitle);
		title.setText(getString(R.string.template_question));
		listTemplate = (ListView) findViewById(R.id.listtemplate);
		templateAdapter = new FeedbackTemplateListAdapter(this);
		loadData();
		setControls();
	}
	
	private void loadData(){
		showProgressDlg();
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				Message msg = handler.obtainMessage();
				List<FeedbackTemplate> templates = null;
				try {
					templates = WireFrameServiceFactory.getInstance().getService().getFeedbackTemplate();
				} catch (Exception e) {
					msg.arg1 = WFErrorCode.NETWORK_ERROR.getValue();
					e.printStackTrace();
				}
				
				msg.obj = templates;
				handler.sendMessage(msg);
			}
		});
		thread.start();
	}
	private Handler handler = new Handler(){
		public void handleMessage (Message msg){
			dismissProgressDlg();
			if(msg.arg1==WFErrorCode.NETWORK_ERROR.getValue()){
				showNetworkErrorDlg();
				return;
			}
			if(msg.obj!=null){
				List<FeedbackTemplate> obj = (List<FeedbackTemplate>) msg.obj;
				templateAdapter.setListFeedbackTemplate(obj);
				listTemplate.setAdapter(templateAdapter);
			}
		}
	};
	private void setControls(){
		listTemplate.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				FeedbackTemplate template = (FeedbackTemplate) templateAdapter.getItem(arg2);
				Intent data = new Intent();
				data.putExtra(Const.TEMPLATEID, template.getId());
				setResult(RESULT_OK, data);
				finish();
			}
		});
	}
}
